<!-- z-paging聊天item -->

<template>
	<view class="message">
		<view v-if="item.msg_type == 'sys_notice'" class="sys_notice">
			<text class="sys_notice__text">{{item.content_text[0].text.content}}</text>
		</view>
		<view style="display: flex;position: relative;" v-else>
			<template v-if="multipleChoice.select">
				<view style="position: absolute;top: 0;left: 0;right: 0;bottom: 0;z-index: 999;"
					@click.stop="clickitem"></view>
				<view class="checkview">
					<image src="/static/icon/select.svg" mode="" style="width: 36rpx;height: 36rpx;"
						v-if="multipleChoice.data.some(it => it.msg_id == item.msg_id)"></image>
					<view style="width: 36rpx;height: 36rpx;" v-else-if="item.msg_type == 'r_p' || item.msg_type == 'd_r'"></view>	
					<image src="/static/icon/no-select.png" mode="" style="width: 36rpx;height: 36rpx;" v-else></image>
				</view>
			</template>
			<view class="message__item" :class="isMe(item.sender_id) ? 'right' : 'left'">
				<view @longpress.stop="avaterlong" @click.stop="avaterClick"
					style="width: 80rpx;height: 80rpx;overflow: hidden;">
					<cl-avatar
						:src="isMe(item.sender_id) ? user_info && user_info.avatar_url : userInfoOther && userInfoOther.avatar_url || ''"
						size="80rpx"></cl-avatar>
				</view>


				<view style="display: flex;flex-direction: column;">
					<view v-if="!isMe(item.sender_id)" class="nametext">
						{{userInfoOther && (userInfoOther.group_nickname || userInfoOther.user_nickname)}}
						<text v-if="userInfoOther.role == 'creator'" class="typetag"
							style="background-color: #52AAFF;">{{$t("group.common.creator")}}</text>
						<text class="typetag"
							v-if="userInfoOther.role == 'manager'">{{$t("group.common.manage")}}</text>
						<text class="typetag"
							v-if="userInfoOther.user_type && userInfoOther.user_type > 0 && userInfoOther.user_type != 6 && userInfoOther.user_type != 8"
							style="background-color: #02D478;">{{$t("common.friend.authority")}}</text>
						<view v-if="getPermission('show_ip')">
							<text>{{item.ip}}</text>
							<text v-if="item.ip_addr">({{item.ip_addr}})</text>
						</view>
					</view>
					<view class="contentview">
						<view style="display: flex;" class="msgcontent" :id="'id'+item.msg_id" @longpress.stop="long"
							@touchend="touchEnd" @touchmove="touchMove">
							<view class="content" :style="{backgroundColor:['image', 'video','r_p','d_r'].includes(item.msg_type)?'transparent':'#ffffff'}"
								:class="{other:['b_c', 'mixed', 'image', 'video','r_p','d_r'].includes(item.msg_type)}">
								<template v-if="item.msg_type == 'text'">
									<rich-text :nodes="messageText(item.content_text[0].text.content)"
										:selectable="false"
										style="-webkit-touch-callout: none;white-space: pre-wrap;overflow-wrap: break-word;color:#333333"
										@itemclick="atClick"></rich-text>
								</template>
								<template v-if="item.msg_type == 'd_r'">
									<cl-chat-dice-tag :item="item.content_text[0].d_r" :all-item="item"></cl-chat-dice-tag>
								</template>
								<template v-if="item.msg_type == 'r_p'">
									<cl-chat-red-packet-group @clickRed="clickRed" :item="item"></cl-chat-red-packet-group>
								</template>
								<template v-else-if="item.msg_type == 'mixed'">
									<cl-chat-img-video :imgList="mediaAttachments(item)" :localId="item.local_id" isChat
										v-if="mediaAttachments(item).length!=0"
										:msgindex="msgindex"></cl-chat-img-video>
									<view v-for="(attachment, arrindex) in item.content_text" :key="arrindex">
										<view v-if="attachment.text" style="margin: 15rpx 10rpx;">
											<rich-text :nodes="messageText(attachment.text.content)" :selectable="false"
												style="-webkit-touch-callout: none;white-space: pre-wrap;overflow-wrap: break-word;color:#333333"></rich-text>
										</view>
									</view>
								</template>
								<template v-else-if="item.msg_type == 'image'">
									<cl-chat-img-video :imgList="item.content_text" :localId="item.local_id" isChat
										:msgindex="msgindex"></cl-chat-img-video>
								</template>
								<template v-else-if="item.msg_type == 'video'">
									<cl-chat-img-video :imgList="item.content_text" isChat
										:localId="item.local_id"></cl-chat-img-video>
								</template>
								<template v-else-if="item.msg_type == 'b_c'">
									<view class="cardview" @click="mingpian">
										<view class="cardview__top">
											<cl-avatar :src="item.content_text[0].b_c.avatar_url"
												size="80rpx"></cl-avatar>
											<text
												class="cardview__top__nickname u-line-1">{{item.content_text[0].b_c.nick_name}}</text>
										</view>
										<view
											style="width: 100%;height: 2rpx;margin: 15rpx 0 5rpx;background-color: #ebebeb;">
										</view>
										<text class="cardview__bottom">
											{{item.content_text[0].b_c.type == 'private'?$t('chat.msg.type.personalCard'):item.content_text[0].b_c.type == 'group'?$t('chat.msg.type.groupCard'):$t('chat.msg.type.otherCard')}}
										</text>
									</view>
								</template>
								<template v-else-if="item.msg_type == 'audio'">
									<cl-chat-audio :audiodata="item.content_text[0].audio" :isme="isMe(item.sender_id)"
										:msg_id="item.msg_id"></cl-chat-audio>
								</template>
							</view>
							<!-- <image src="../../static/chat/fanyi.png" mode="" style="width: 50rpx;height: 50rpx;" v-if="!isMe(item.sender_id) && (item.msg_type == 'text' || (item.msg_type == 'mixed' && isText))" @click="$emit('translate',item)"></image> -->
							
							<view
								style="display: flex;gap: 15rpx;font-size: 22rpx;align-self: self-end;margin-left: 10rpx;flex-wrap: wrap;"
								v-if="item.is_review == 0 && !isMe(item.sender_id)">
								<text style="color: aqua;" @click="shenheClick('agree')">通过</text>
								<text style="color: red;" @click="shenheClick('rejective')">拒绝</text>
							</view>
							<view class="statusview" v-if="isMe(item.sender_id)">
								<u-loading-icon mode="circle" size="14"
									v-if="item.msg_status == 'lodding'"></u-loading-icon>
								<view style="display: inline-block;border-radius: 50%;background-color: #fff;"
									v-if="item.msg_status == 'failed'" @click="retransmission">
									<u-icon name="error-circle-fill" color="#ff0000" size="14"></u-icon>
								</view>
								<view class="" v-if="item.msg_status == 'read'">
									<u-icon name="checkmark-circle"></u-icon>
								</view>
							</view>
						</view>
						<view v-if="item.ref_msg_id && item.ref_msg_id != '0' && item.ref_msg_id != '' && refMsgItem" class="refClass" @click="refClick">
							<view style="flex: 1;" v-if="refMsgItem.msg_type == 'text'">
								<text style="color: #1c93cf;font-size: 26rpx;">{{refMsgItem.sender_id == user_info.user_id ? user_info.nick_name : getUserInfo(refMsgItem.sender_id).group_nickname || getUserInfo(refMsgItem.sender_id).user_nickname || ''  }}</text>
								<view class="u-line-1">
									<rich-text
										:nodes="refMsgItem.content_text && refMsgItem.content_text.length &&replaceEmojis(refMsgItem.content_text[0].text.content)"
										:selectable="false"
										style="-webkit-touch-callout: none;white-space: pre-wrap;overflow-wrap: break-word;color:#666666;font-size: 24rpx;"></rich-text>
								</view>
							</view>
							<view style="flex: 1;" v-else-if="refMsgItem.msg_type == 'audio'">
								<text style="color: #1c93cf;font-size: 26rpx;">{{refMsgItem.sender_id == user_info.user_id ? user_info.nick_name : getUserInfo(refMsgItem.sender_id).group_nickname || getUserInfo(refMsgItem.sender_id).user_nickname || ''  }}</text>
								<view class="u-line-1" style="color:#666666;font-size: 24rpx;">
									{{$t("chat.msg.type.audio")}}
								</view>
							</view>
							<view style="flex: 1;" v-else-if="refMsgItem.msg_type == 'b_c'">
								<text
									style="color: #1c93cf;font-size: 26rpx;">{{refMsgItem.sender_id == user_info.user_id ? user_info.nick_name : getUserInfo(refMsgItem.sender_id).group_nickname || getUserInfo(refMsgItem.sender_id).user_nickname || ''  }}</text>
								<view class="u-line-1" style="color:#666666;font-size: 24rpx;">
									{{$t("chat.msg.type.b_c")}}
								</view>
							</view>
							<view style="display: flex;flex: 1;align-items: flex-start;" v-else>
								<view style="width: 68rpx;height: 68rpx;margin-right: 5rpx;"
									v-if="mediaAttachmentsOne(refMsgItem).url">
									<cl-chat-image :key="mediaAttachmentsOne(refMsgItem).url"
										:srckey="mediaAttachmentsOne(refMsgItem).url"
										:imageStyle="{width: '68rpx',height:'68rpx'}" :noclick="true"></cl-chat-image>
								</view>
								<view style="flex: 1;margin-top: -10rpx;">
									<text style="color: #1c93cf;font-size: 26rpx;">{{refMsgItem.sender_id == user_info.user_id ? user_info.nick_name : getUserInfo(refMsgItem.sender_id).group_nickname || getUserInfo(refMsgItem.sender_id).user_nickname || ''  }}</text>
									<view class="u-line-1" v-if="mediaAttachmentsOne(refMsgItem).text">
										<rich-text :nodes="mediaAttachmentsOne(refMsgItem).text" :selectable="false"
											style="-webkit-touch-callout: none;white-space: pre-wrap;overflow-wrap: break-word;color:#666666;font-size: 24rpx;"></rich-text>
									</view>
								</view>
							</view>
						</view>
						<!-- <view v-if="item.translate_json && item.translate_json.show" class="fanyiview">
							<rich-text :nodes="messageText(item.translate_json.text)" :selectable="false"
								style="-webkit-touch-callout: none;white-space: pre-wrap;overflow-wrap: break-word;color:#dddddd"></rich-text>
						</view> -->
						<text class="timertext"
							style="font-size: 24rpx;color:#5B5A63;">{{formatSendTime(item.create_time)}}</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapActions,
		mapState
	} from 'vuex'
	import {
		replaceEmojis
	} from '@/components/cl-chat-input/o-emoji/emoji.js';
	import {
		formatSendTime
	} from '@/common/chatMsgTime.js'
	import groupMembersApi from "@/services/api/group_members.js"
	import msgSqlite from "@/sqlite_services/msg.js"
	export default {
		name: "chat-item-group",
		props: {
			item: {
				type: Object,
				default: function() {
					return {}
				}
			},
			multipleChoice: {
				default: function() {
					return {
						select: false,
						data: []
					}
				}
			},
			msgindex: {
				type: String | Number,
				default: '0'
			}
		},
		computed: {
			...mapState({
				// users: state => state.userinfo.users,
				user_info: state => state.user.user_info,
				chatInfo: state => state.chat.chatInfo,
				chatGroupInfo: state => state.chat.chatGroupInfo,
				groupMemberInfo: state => state.groupMembersInfo.groupMemberInfo,
			}),
			isText(){
				return this.item.content_text.some(item => item.text !== undefined);
			},
			getPermission() {
				return (type) => {
					if (this.chatGroupInfo == null || this.chatGroupInfo.mygroup == '0') return false
					// 0所有人 1普通用户 2管理员 3都不允许
					if (this.chatGroupInfo[type] == '0') {
						return true
					} else if (this.chatGroupInfo[type] == '1') {
						if (this.chatGroupInfo.userRole && this.chatGroupInfo.userRole != 'manager') return true
					} else if (this.chatGroupInfo[type] == '2') {
						if (this.chatGroupInfo.userRole && this.chatGroupInfo.userRole != 'member') return true
					} else if (this.chatGroupInfo[type] == '3') {
						if (this.chatGroupInfo.userRole && this.chatGroupInfo.userRole == 'creator') return true
					}
					return false
				}
			},
			userInfoOther() {
				if (this.item.msg_type == 'sys_notice') {
					return {}
				}
				let useitem = this.groupMemberInfo[this.item.sender_id]
				if (useitem) {
					return useitem
				}
				return {}
			},
			getUserInfo(){
				return (uid) => {
					let useitem = this.groupMemberInfo[uid]
					if (useitem) {
						return useitem
					}
					return {}
				}
			},
			isMe() {
				return (uuid) => {
					if (uuid == this.user_info.user_id) return true
					return false
				}
			},
			messageText() {
				return (text) => {
					return replaceEmojis(text)
				}
			},
			mediaAttachments() {
				return (item) => {
					return item.content_text.filter(a => a.image || a.video);
				}
			}
		},
		watch: {
			'item.ref_msg_id': {
				deep: true,
				immediate: true,
				handler(newVal) {
					if (newVal && newVal != '' && newVal != '0') {
						this.getRefMsgItem()
					}
				}
			}
		},
		data() {
			return {
				ifLongtap: true,
				a: 0,
				refMsgItem: null,
			};
		},
		created() {
			// 在组件创建时检查并获取用户信息
			if (this.item.msg_type != 'sys_notice' && this.item.sender_id != this.user_info.user_id && !this
				.groupMemberInfo[this.item.sender_id]) {
				this.fetchGroupUserInfo({
					userId: this.item.sender_id,
					groupId: this.chatInfo.uuid
				});
			}
			console.log(this.item);
		},
		methods: {
			replaceEmojis,
			formatSendTime,
			...mapActions(['fetchGroupUserInfo']),
			refClick(){
				this.$Router.push({
					name:'msg_top',
					params: {
						chat_type:'private',
						chatTopMsg:this.refMsgItem,
						type:'quote',
					}
				})
			},
			clickRed(item){
				console.log(item);
				this.$emit('clickRed',item)
			},
			//获取回复的媒体消息
			mediaAttachmentsOne(item) {
				let mediaAttachments = item.content_text.filter(a => a.image || a.video);
				let getTexts = item.content_text.filter(e => e.text)
				console.log(item);
				let text = getTexts.length ? getTexts[0].text.content : ''
				if (mediaAttachments.length) {
					if (mediaAttachments[0].image) {
						return {
							url: mediaAttachments[0].image.url,
							text
						}
					} else if (mediaAttachments[0].video) {
						return {
							url: mediaAttachments[0].video.thumb_url,
							text
						}
					} else {
						return {
							url: null,
							text
						}
					}
				} else {
					return {
						url: null,
						text
					}
				}
			},
			async getRefMsgItem() {
				try {
					let msgItem = await msgSqlite.getMsgIdItem(this.item.ref_msg_id)
					msgItem.content_text = JSON.parse(msgItem.content_text)
					this.refMsgItem = msgItem
				} catch (e) {
					console.log(e);
					//TODO handle the exception
				}
			
			},
			atClick(e) {
				uni.$u.throttle(async () => {
					if (e.target.node.name == 'a' && e.target.node.atid) {
						if (e.target.node.atid == this.$store.state.user.user_info.user_id || e.target.node
							.atid == 'all') {
							return
						}

						if (!this.getPermission('can_add_friends')) {
							uni.showToast({
								title: this.$t("group.group_members.memberBeingProtected"),
								icon: 'none'
							})
							return
						}
						try {
							let friendRes = await uni.$api.friends.isFriend({
								friend_id: e.target.node.atid
							})
							if (friendRes && friendRes.data.is_friend) {
								this.$Router.push({
									name: 'friend_details',
									params: {
										friend_idx: e.target.node.atid,
										skipAgain: true, //再次进入聊天页面,
										groupNickname: e.target.node.atname,
									}
								});
								return
							}
						} catch (e) {}
						this.$Router.push({
							name: 'add_member_details',
							params: {
								user_id: e.target.node.atid,
								isGroupGo: true,
								groupNickname: e.target.node.atname,
							}
						});
					}
				}, 1000)
			},
			//消息审核
			async shenheClick(type) {
				let req_status;
				switch (type) {
					case 'agree':
						req_status = '1'
						break;
					case 'rejective':
						req_status = '2'
						break;
					default:
						break;
				}
				if (req_status) {
					try {
						let res = await this.$api.chat.GroupAuditing({
							msg_id: this.item.msg_id,
							conversation_id: this.item.conversation_id,
							target_id: this.chatInfo.uuid,
							req_status
						})
						if (res) {
							this.item.is_review == req_status
							console.log(res);
						}
					} catch (e) {
						//TODO handle the exception
					}
				}
			},
			async avaterlong() {
				//如果不是我
				if (this.item.sender_id != this.user_info.user_id) {
					try {
						let res = await groupMembersApi.getGroupMemberInfo({
							group_id: this.chatInfo.uuid,
							members: [this.item.sender_id]
						})
						if (res) {
							this.$emit('avaterlong', {
								...this.item,
								...res[0]
							})
						}
					} catch (e) {
						//TODO handle the exception
					}


				}
			},
			async avaterClick() {
				uni.$u.throttle(async () => {
					if (this.item.sender_id == this.$store.state.user.user_info.user_id) {
						return
					}
					if (!this.getPermission('can_add_friends')) {
						uni.showToast({
							title: this.$t("group.group_members.memberBeingProtected"),
							icon: 'none'
						})
						return
					}
					try {
						let friendRes = await uni.$api.friends.isFriend({
							friend_id: this.userInfoOther.user_id
						})
						if (friendRes && friendRes.data.is_friend) {
							this.$Router.push({
								name: 'friend_details',
								params: {
									friend_idx: this.userInfoOther.user_id,
									avatar_url: this.userInfoOther.avatar_url,
									nick_name: this.userInfoOther.user_nickname,
									skipAgain: true, //再次进入聊天页面
									groupNickname: this.userInfoOther.group_nickname || this
										.userInfoOther.nick_name,
								}
							});
							return
						}
					} catch (e) {}
					this.$Router.push({
						name: 'add_member_details',
						params: {
							user_id: this.userInfoOther.user_id,
							nick_name: this.userInfoOther.nick_name,
							avatar_url: this.userInfoOther.avatar_url,
							isGroupGo: true,
							groupNickname: this.userInfoOther.group_nickname || this.userInfoOther
								.nick_name,
						}
					});
				}, 1000)
			},
			clickitem(e) {
				if(this.item.msg_type == 'r_p' || this.item.msg_type == 'd_r')return
				if (this.multipleChoice.select) {
					if (this.multipleChoice.data.some(item => item.msg_id == this.item.msg_id)) {
						// 如果数组中包含特定值，则删除该值
						const index = this.multipleChoice.data.findIndex(item => item.msg_id == this.item.msg_id);
						this.multipleChoice.data.splice(index, 1);
					} else {
						// 如果数组中不包含特定值，则添加该值
						this.multipleChoice.data.push(this.item);
					}
				}
			},
			async mingpian() {
				uni.$u.throttle(async () => {
					let {
						card_user_id,
						nick_name,
						avatar_url,
						type
					} = this.item.content_text[0].b_c
					if (type == 'private') {
						if (card_user_id == this.$store.state.user.user_info.user_id) {
							return
						}
						if (!this.getPermission('can_add_friends')) {
							uni.showToast({
								title: this.$t("group.group_members.memberBeingProtected"),
								icon: 'none'
							})
							return
						}
						try {
							let friendRes = await uni.$api.friends.isFriend({
								friend_id: card_user_id
							})
							if (friendRes && friendRes.data.is_friend) {
								this.$Router.push({
									name: 'friend_details',
									params: {
										friend_idx: card_user_id,
										avatar_url: avatar_url,
										nick_name: nick_name,
										skipAgain: true, //再次进入聊天页面
									}
								});
								return
							}
						} catch (e) {}
						this.$Router.push({
							name: 'add_member_details',
							params: {
								user_id: card_user_id,
								nick_name: nick_name,
								avatar_url: avatar_url,
								isGroupGo: true
							}
						});
					}
				}, 1000)
			},
			retransmission() {
				this.$emit('repeater', this.item)
			},
			//判断两个时间差是否大于5分钟
			compareTimeInterval(t1, t2) {
				return t1 - t2 >= 300000 ? true : false;
			},
			touchEnd() {
				this.ifLongtap = true;
			},
			touchMove(e) {
				// 手指触摸后的移动事件
				this.ifLongtap = false;
			},
			long(e) {
				console.log(this.item);
				if (this.ifLongtap) {
					let x = 0
					let y = 0
					let place = ''
					let dom = uni.createSelectorQuery().in(this);
					console.log(this.item.msg_id);
					dom.select('#id' + this.item.msg_id).boundingClientRect();
					dom.exec(data => {
						console.log(data);
						let isTop = data[0].top >= 44 + this.$u.sys().statusBarHeight + 105,
							place = isTop ? 'bottom' : 'top';
						place = place + '-center';
						x = data[0]['left'];
						y = data[0][isTop ? 'top' : 'bottom'];
						this.$emit('long', {
							x,
							y,
							width: data[0]['width'],
							place,
							item: this.item
						})
					});
				}
			},
		}
	}
</script>
<style scoped lang="scss">
	.cardview {
		width: 400rpx;
		padding: 15rpx 15rpx 10rpx;

		&__top {
			display: flex;
			align-items: center;

			&__nickname {
				margin-left: 15rpx;
				font-size: 28rpx;
			}
		}

		&__bottom {
			font-size: 20rpx;
			color: #61626e;
		}
	}

	.message {
		padding: 20rpx 20rpx;
		box-sizing: border-box;


		.sys_notice {
			display: flex;
			justify-content: center;

			&__text {
				// background-color: rgba(30, 31, 48, 0.8);
				text-align: center;
				font-size: 26rpx;
				color: #858491;
				padding: 8rpx 20rpx;
				max-width: 80%;
				border-radius: 30rpx;
			}
		}

		.checkview {
			margin-top: 22rpx;
			margin-right: 20rpx;
		}

		&__timeview {
			display: flex;
			justify-content: center;
			padding: 0 0 20rpx;

			&__time {
				font-size: 20rpx;
				color: #5B5A63;
				line-height: 28rpx;
			}
		}

		&__item {
			flex: 1;
			display: flex;
			justify-content: flex-start;
			align-items: flex-start;
			align-content: flex-start;
			flex-wrap: nowrap;
			flex-direction: row;

			.nametext {
				margin-bottom: 10rpx;
				font-size: 22rpx;
				color: #888992
			}

			.contentview {
				display: flex;
				flex-direction: column;
				.refClass{
					display: flex;
					max-width: 480rpx;
					background-color: rgba(255, 255, 255, 0.6);
					border-radius: 15rpx;
					padding: 10rpx 20rpx;
					margin-top: 10rpx;
				}
				.fanyiview{
					max-width: 480rpx;
					background-color: rgba(0, 0, 0, 0.2);
					border-radius: 15rpx;
					padding: 10rpx 20rpx;
					margin-top: 10rpx;
					font-size: 32rpx;
				}
				
				.msgcontent {
					// align-self: self-start;
				}
				.content {
					padding: 20rpx;
					max-width: 480rpx;
					border-radius: 15rpx;
					font-size: 32rpx;
					background: #ffffff;
					align-self: self-start;

					&.other {
						padding: 3rpx;
						margin: 0;
					}
				}

				
			}

			
			.statusview {
				align-self: flex-end;
			}
			&.right {
				flex-direction: row-reverse;

				.nametext {
					margin-right: 20rpx;
				}


				.statusview {
					margin-right: 10rpx;
				}

				.contentview {
					margin-right: 20rpx;
					align-items: flex-end;
					.msgcontent {
						flex-direction: row-reverse;
					}
					.content {
						word-wrap: break-word;
						line-height: 36rpx;
						position: relative;
					}
				}

			}

			&.left {
				.nametext {
					margin-left: 20rpx;
				}


				.statusview {
					margin-left: 10rpx;
				}

				.contentview {
					margin-left: 20rpx;
					align-items: flex-start;
					.content {
						word-wrap: break-word;
						line-height: 36rpx;
						position: relative;
					}
				}
			}
		}
	}

	.typetag {
		white-space: nowrap;
		font-size: 20rpx;
		color: #FFFFFF;
		padding: 0 10rpx;
		height: 28rpx;
		line-height: 28rpx;
		text-align: center;
		border-radius: 10rpx;
		margin-left: 10rpx;
		background-color: #FF7676;
	}
</style>